package algorithms;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by gcqst on 15/10/17.
 */
public class Problem290 {
    public static boolean wordPattern(String pattern, String str){
        if(str == null)
            return false;
        String[] array = str.split(" ");
        if(array.length != pattern.length())
            return false;

        Map<String, Character> map1 = new HashMap<String,Character>();
        int i = 0;
        for(String s : array){
            if(map1.containsKey(s)){
                if(!map1.get(s).equals(pattern.charAt(i)))
                    return false;
            } else{
                map1.put(s, pattern.charAt(i));
            }
            i++;
        }

        Map<Character,String> map2 = new HashMap<Character,String >();
        i = 0;
        for(char c : pattern.toCharArray()){
            if(map2.containsKey(c)){
                if(!map2.get(c).equals(array[i]))
                    return false;
            } else{
                map2.put(c, array[i]);
            }
            i++;
        }

        return true;
    }

    public static void main(String[] args){
        String pattern = "abba";
        String str = "dog cat cat dog";
        System.out.println(wordPattern(pattern,str));
    }
}
